package com.study.spmongodb.book.wwj.char08;

/**
 * @author MI
 * @version 1.0
 * @date 2020/11/25 23:01
 */
public class InternalTask implements Runnable {
    private final RunnableQueue runnableQueue;
    private volatile boolean running = true;

    public InternalTask(RunnableQueue runnableQueue) {
        this.runnableQueue = runnableQueue;
    }


    /**
     * 当前 任务为 running 并且没有被中断，则将其不断地从queue中获取 runnable ，然后执行run方法。
     */
    @Override
    public void run() {
        while (running && !Thread.currentThread().isInterrupted()) {
            try {
                Runnable take = runnableQueue.take();
                take.run();
            } catch (Exception e) {
                running = false;
                break;
            }
        }
    }

    /**
     * 停止当前任务，主要会在线程池的shutdown方法中使用。
     */
    public void stop() {
        this.running = false;
    }
}
